package com.saobao.m.assistant.controller;

import com.alibaba.fastjson.JSON;
import com.saobao.m.assistant.dao.UserDAO;
import com.saobao.m.assistant.domain.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author sunruifeng
 * @since 15/2/3 上午10:41
 */
@Controller
@Slf4j
public class IndexController {
    @Resource
    private UserDAO userDAO;

    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request) {
        log.info(request.getParameterMap().toString());
        return "index";
    }

    @RequestMapping(value = "/insert/{name}/{age}/{sex}")
    public String list(@PathVariable("name") String name,
                       @PathVariable("age") Integer age,
                       @PathVariable("sex") String sex,
                       Model model) {
        UserDO user = new UserDO();
        user.setAge(age);
        user.setName(name);
        user.setSex(sex);
        userDAO.insert(user);

        model.addAttribute("users", userDAO.listAll());
        return "list";
    }
    @RequestMapping(value = "/list")
    @ResponseBody
    public String listUsers(){
        return JSON.toJSONString(userDAO.listAll());
    }

}
